package com.chen.seckill.config;

import com.chen.seckill.pojo.User;
import com.chen.seckill.resultvo.RespBean;
import com.chen.seckill.resultvo.RespBeanEnum;
import com.chen.seckill.service.IUserService;
import com.chen.seckill.utils.CookieUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 自定义拦截器
 * 作用：实现AccessLimit注解功能
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {


    @Resource
    private IUserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if (handler instanceof HandlerMethod){
            User user=getUser(request,response);
            //将user存储在UserContext中
            UserContext.setUser(user);
           HandlerMethod hm = (HandlerMethod) handler;
           AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
           //如果method上没有AccessLimit注解，直接放行
           if (accessLimit==null){
               return true;
           }
           int second= accessLimit.second();
           int maxCount= accessLimit.maxCount();
           boolean needLogin=accessLimit.needLogin();
           String uri = request.getRequestURI();
           if (needLogin){
               if (user==null){
                   render(response, RespBeanEnum.SESSION_ERROR);
                   return false;
               }
               uri+=":"+user.getId();
               ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
               /**
                * 介绍：限制访问次数
                * 要求20秒内最多访问5次
                */
               Integer count = (Integer) valueOperations.get(uri);
               if (count==null){
                   valueOperations.set(uri,1,second, TimeUnit.SECONDS);
               }else if (count<maxCount){
                   valueOperations.increment(uri);
               }else {
                   render(response,RespBeanEnum.ACCESS_LIMIT_REQUEST);
                   return false;
               }
           }

       }
       return  true;
        // return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 构建返回对象
     * @param response
     * @param sessionError
     */
    private void render(HttpServletResponse response, RespBeanEnum sessionError) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        RespBean respBean = RespBean.error(sessionError);
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }

    /**
     * 获取当前用户
     * @param request
     * @param response
     * @return
     */
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        //System.out.println(ticket);
        if (StringUtils.isEmpty(ticket)){
            return null;
        }
        User user=userService.getUserByCookie(ticket,request,response);
       // System.out.println(user+"**********************");
        return user;
    }


}
